import {AsyncStorage} from 'react-native';

import {observable} from 'mobx';

class UserStore {
    localStorageKeyPrefix = 'user';

    @observable loggedIn = false;
    openid = null;
    unionid = null;
    headimgurl = null;
    nickname = null;
    sex = null;
    city = null;
    province = null;
    country = null;
    wechatLoginInfo = {
        openid: null,
        unionid: null,
        headimgurl: null,
        nickname: null,
        sex: null,
        city: null,
        province: null,
        country: null,
    };

    init() {};

    async login() {
        this.loggedIn = true;
        try {
            await AsyncStorage.setItem('user:loggedIn', JSON.stringify(this.loggedIn));
        } catch(err) {
            console.log(`Error occurred while saving login status to local ${err}`);
            throw err;
        }
        console.log('Persisted user login info to store')
    }

    loginWechat(...params) {
        this.wechatLoginInfo = {
            ...this.wechatLoginInfo,
            ...params,
        };
    };

    clearWechatLoginInfo() {
        for (const k in this.wechatLoginInfo) {
            this.wechatLoginInfo[k] = null;
        }
    };

    async _loadLocalStorage() {
        let storeKeys = [];
        let localStorageKeys = [];
        for (const key in this) {
            if (typeof(this[key]) === 'object' || typeof(this[key]) === 'function') {
                continue;
            }
            storeKeys.push(key);
            localStorageKeys.push([this.localStorageKeyPrefix, key].join(':'));
        }
        localStorageValues = await AsyncStorage.multiGet(localStorageKeys);
    }
}

const userStore = new UserStore();

export default userStore;
